`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: CBICR, Tsinghua Univ.
// Engineer: Hongyi Li
// 
// Create Date: 2024/12/24 12:24:54
// Design Name: 
// Module Name: Arbitor
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////


module RoundRobinArbitor
#(
    parameter N = 'd4
)(
    input          clk, rst_n,
    input  [N-1:0] i_req,
    output [N-1:0] o_grant
);

reg  [N - 1 : 0] last_state;
wire [2 * N - 1 : 0] next_grant;

always @(posedge clk) begin
    if (!rst_n) 
        last_state <= 'd1;
    else if (|i_req)
        last_state <= {o_grant[N-2:0], o_grant[N-1]};
    else
        last_state <= last_state;
end

assign next_grant = {i_req, i_req} & ~({i_req, i_req} - last_state);
assign o_grant = next_grant[2*N-1:N] | next_grant[N-1:0];

endmodule